<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" style="margin-bottom: 20px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table ref="dataTable" v-loading="loading" :row-key="getRowKey" :data="roleList" @select="handSelect" @select-all="handleMultipleRoleSelect">
      <el-table-column type="selection" width="50" align="center" reserve-selection/>
      <el-table-column label="角色编号" prop="roleId" width="120" />
      <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="显示顺序" prop="roleSort" width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page-sizes="[5,10]"
        layout="prev, pager, next"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>

<script setup name="FlowRole">
import { listRole } from "@/api/system/role";
import {markRaw} from "@vue/reactivity";
import {StrUtil} from "@/utils/StrUtil";
const router = useRouter();
const { proxy } = getCurrentInstance();

const roleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectedRows = ref([]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 5,
    roleName: undefined,
  },
});

const { queryParams } = toRefs(data);

const emit = defineEmits(['handleAssignSelect'])

/** 组件传值  */
const props = defineProps({
  // 回显数据传值
  selectData: {
    type: Array,
    default: () => [],
    required: false
  },
});

/** 查询角色列表 */
function getList() {
  loading.value = true;
  listRole(queryParams.value).then(response => {
    roleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    proxy.$nextTick(() => {
      // 打开时回显数据
      echoChooseItems();
    });
  });
}

// 已选数据
selectedRows.value = props.selectData?.map(item => ({
  roleId: item.id ?? item.roleId,
  roleName: item.name ?? item.roleName
})) ?? [];

selectDataChange();

// 选中数据变化
function selectDataChange(){
  emit('handleAssignSelect', markRaw(selectedRows.value));
}

// 回显（勾选）已选事项
function echoChooseItems() {
  selectedRows.value.forEach(selectRow => {
    const index = roleList.value.findIndex(item => item.roleId.toString() === selectRow.roleId.toString());
    if (index !== -1) {
      proxy.$refs["dataTable"].toggleRowSelection(roleList.value[index], true);
    }
  });
}

// 单选框选中数据
function handSelect(selection, row) {
  if (selectedRows.value.findIndex(selectRow => selectRow.roleId.toString() === row.roleId.toString()) < 0) {
    selectedRows.value.push(row);
  } else {
    // 回显数据里有本条，把这条删除(取消选中)
    selectedRows.value.forEach((selectRow, index) => {
      if (selectRow.roleId.toString() === row.roleId.toString()) {
        selectedRows.value.splice(index, 1);
      }
    });
  }
  emit('handleAssignSelect', markRaw(selectedRows.value));
}

// 全选数据
function handleMultipleRoleSelect(selection) {
  if (selection.length > 0) {
    selection.forEach((item) => {
      if (!selectedRows.value.includes(item.roleId.toString())) {
        selectedRows.value.push(item);
      }
    });
  } else {
    roleList.value.forEach((item) => {
      selectedRows.value.forEach((selectRow, index) => {
        if (selectRow.roleId.toString() === item.roleId.toString()) {
          selectedRows.value.splice(index, 1);
        }
      });
    });
  }
  emit('handleAssignSelect', markRaw(selectedRows.value));
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 保存选中的数据id,row-key就是要指定一个key标识这一行的数据 */
function getRowKey (row) {
  return row.roleId
}

getList();
</script>
